import 'dart:convert';
import 'dart:typed_data';
import 'package:pointycastle/export.dart';
import 'package:asn1lib/asn1lib.dart';
import 'package:pointycastle/export.dart' as pc;


class SignService {
  /// 新的私钥（对应PHP中test方法使用的私钥）
  static const String newPrivateKey = '''MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC0/zOK/JOZ47Nq
CNXaGc6tYxmg1e+K0pYLbV9+XUjBKG7vclJkD3+5jMmVharX/pbo2JHCd3yBmlDV
m3BWTGK0rctICkx3p6ArxoIkW5yyAYc/b62B49JVFpIpxrFEXeCIFsrmdwmTLh30
ABewRMSZ6ApylN2PGi+kLfDoURO1tY5dgz1BRsPScX6XlOt3yzyaEPB6WFa91DLi
hvaDJThcApR0Yubsp0MZUaZf5WWeBIZGo1RE/H2bf2kPb/5WZZjG3GlRWYJzTuGh
nWZSurhrf4qDVH9o1Hbqv7H+YmgiPjYvzFWm0Ixx0c88jvSBx/7gs4X5NVIyhafV
TNgFsCIRAgMBAAECggEACf8ENjtf3YJtYMBPK0X8m6fa/P6Dxct+nO/z87MsNvrI
MbJDKaKPf8xuP7NLrbUyWXbIihB2UGQY7csxZ5q9YtQsY3SqJ3ubBX/npSFoJI6g
DRlaYE+YSLm/5c3C8Y8rvOhhWVweq8HCxryQklwh7Ywas5xUJjigg/VDllkP+RuP
af3/qGkfe7bk89BLgmTOBoBmMe1cohYpi+3up30/GV3zV1LOIrvUeX0E05+MGqF7
MapQ7t/GKMNXtSUJpcMmzsU9ExkVVKiEP9E7F1ybd4vu07ZuNoujE+Jt6B/NJXoY
3r+L+Fim1/xZgcSOGzjoyt/kNqHjYQYlOXTiNPHi/wKBgQDyDJCUjK4ke90ZoHat
5018WVZiiR7/76CqQ1C0CLsmrTL2/iyUWfi44Jlh+FevGILcJWb2kgL4w5T//+I3
MUO2xACfbiPMU/F4Dgl0l9urXqZtliKYYAjoGbKAQuxhtqyDBlIrBsOSVt39IvJt
IbO4aZfOG6xFPsL7MVKDF5Ao/wKBgQC/bc+jVieJLS1U91AUtKV4cTfV0HAB735I
pFdavlH63XPdu/CNYWwThHhOiz6oikZNAYyHfGS0cNRYZ7v6XcOrD58me2fBq2G7
vSHLtQWuOnmIdUryCMU4ETOLKf6Cz6HNIVBi3IzE32vPr95irueJ63FdFZSB+lYf
64L3eaok7wKBgQCKGM8YYdctK5ou99UeTPxxeMsHdvI/1WjWG4fc36pfW6vbLZMj
pN16JXJ9aeIlHRf0IEbJYO7fHT9Se5yGHs5iZRtx2rYD6tS2yVNtuQJ0mJDdry3X
v9r1CUxFT2lsKnvsWVvh/n7wbC1FMn4b84GFMoGQ70rvSuqVxEMuVfBC4wKBgCrM
JiviSxyEGSpx0FmQuZ3f0hffbetA2/7pnw4Ols17TTg5mGJDcaI7b5o/z1Zm86ir
u/teeDVPNGo/ZutmoyRPbclwtZW69zK96hxc8FQvhpRXhNXv2Afc8KUgUmJ0gTwX
Qp2XqXEqcjQQoat2ZxWSqdmhxX35td+VC8bAUKXJAoGAUqBNVU87p5gAPBcGj26K
Eisz1wJ8/JkAt9AyMOXsXRQwpCKbeCfFoI65gOZXK9OEabaFUoTplr/Bk6R54uN/
Phv550ezHNBAxjiZGe/z2lOv2zdvR01nekUcZVXUp3c3siu/X9m7ceecLOnYnfc7
AHy4EakweG32o4AWXWDkW0g=''';

  /// 深度排序 - 对应PHP的deep_ksort方法
  void deepKsort(Map<String, dynamic> arr) {
    if (arr is Map) {
      // 获取排序后的键
      var sortedKeys = arr.keys.toList()..sort();
      var sortedMap = <String, dynamic>{};

      for (String key in sortedKeys) {
        var value = arr[key];
        if (value is Map<String, dynamic>) {
          deepKsort(value);
        }
        sortedMap[key] = value;
      }

      arr.clear();
      arr.addAll(sortedMap);
    }
  }

  /// 生成新的字符串 - 对应PHP的deep_new_string方法
  String deepNewString(dynamic arr) {
    String str = '';

    if (arr is Map) {
      arr.forEach((key, val) {
        if (val is Map) {
          val.forEach((valKey, valVal) {
            if (valVal is Map) {
              str += deepNewString(valVal);
            } else {
              // 重要：对应PHP的strtolower，将值转换为小写
              str += '$key.$valKey=${valVal.toString().toLowerCase()}&';
            }
          });
        } else {
          // 重要：对应PHP的strtolower，将值转换为小写
          str += '$key=${val.toString().toLowerCase()}&';
        }
      });
    }

    // 去除末尾的& - 对应PHP的trim($str, '&')
    if (str.endsWith('&')) {
      str = str.substring(0, str.length - 1);
    }

    return str;
  }

  /// 解析 DER 格式的 PKCS8 私钥
  RSAPrivateKey parsePkcs8PrivateKey(Uint8List derBytes) {
    final asn1Parser = ASN1Parser(derBytes);
    final topLevelSeq = asn1Parser.nextObject() as ASN1Sequence;
    final privateKeyOctetString = topLevelSeq.elements[2] as ASN1OctetString;

    final privateKeyParser = ASN1Parser(privateKeyOctetString.octets);
    final pkSeq = privateKeyParser.nextObject() as ASN1Sequence;

    final modulus = (pkSeq.elements[1] as ASN1Integer).valueAsBigInteger!;
    final publicExponent =
        (pkSeq.elements[2] as ASN1Integer).valueAsBigInteger!;
    final privateExponent =
        (pkSeq.elements[3] as ASN1Integer).valueAsBigInteger!;
    final p = (pkSeq.elements[4] as ASN1Integer).valueAsBigInteger!;
    final q = (pkSeq.elements[5] as ASN1Integer).valueAsBigInteger!;

    return RSAPrivateKey(modulus, privateExponent, p, q);
  }

  /// 用 SHA1withRSA 签名数据
String signWithSHA1RSA(String data, String base64Key) {
  // 先解析 base64Key 为 RSAPrivateKey
  final derBytes = base64Decode(base64Key.replaceAll(RegExp(r'\s+'), ''));
  final privateKey = parsePkcs8PrivateKey(derBytes);

  final signer = pc.RSASigner(pc.SHA1Digest(), '06052b0e03021a');

  signer.init(true, PrivateKeyParameter<RSAPrivateKey>(privateKey));

  final signature =
      signer.generateSignature(Uint8List.fromList(utf8.encode(data)));

  return base64Encode(signature.bytes);
}

}
